package com.hb.core.context;

import com.hb.core.model.SecurityClient;
import io.netty.util.concurrent.FastThreadLocal;
import org.apache.commons.lang3.BooleanUtils;

/**
 * @description: 保存当前用户的线程本地对象容组器
 * @projectName: zhb-frame-build
 * @author: zhouhaizhi
 * @createTime: 2021/8/27 14:10
 * @version:1.0
 */
public class CurrentAccountHolder {

    /*
        启用开关容器
     */
    private static final FastThreadLocal<Boolean> SWITCH_FLAG = new FastThreadLocal<>();

    /*
        当前用户容器
     */
    private static final FastThreadLocal<SecurityClient> CURRENT_USER = new FastThreadLocal<>();

    /*
        容器组初始化
     */
    public static void init() {
        SWITCH_FLAG.set(true);
    }

    /*
        开关开启的情况下，将用户放入容器
     */
    public static void set(SecurityClient client) {
        Boolean switchFlag = SWITCH_FLAG.get();
        if (BooleanUtils.isTrue(switchFlag)) {
            CURRENT_USER.set(client);
        }
    }

    /*
        开关开启的情况下，尝试返回容器中的用户
        关闭情况下返回null
     */
    public static SecurityClient get() {
        Boolean switchFlag = SWITCH_FLAG.get();
        if (BooleanUtils.isTrue(switchFlag)) {
            return CURRENT_USER.get();
        } else {
            return null;
        }
    }

    /*
        删除保存的用户
     */
    public static void remove(){
        SWITCH_FLAG.remove();
        CURRENT_USER.remove();
    }
}
